package com.sakura.mybatis.builder;

import com.sakura.mybatis.config.Configuration;
import com.sakura.mybatis.config.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @author wangxinyuchuan
 * @version XmlMapperBuilder.java v1.0 2025/4/15 15:40 wangxinyuchuan Exp $
 */
public class XmlMapperBuilder {

    private final Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        List<Element> selectElements = rootElement.selectNodes("//select");

        selectElements.forEach(element -> {
            String selectId = element.attributeValue("id");
            String parameterType = element.attributeValue("parameterType");
            String resultType = element.attributeValue("resultType");
            String sql = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            String mappedStatementId = namespace + "." + selectId;
            mappedStatement.setStatementId(mappedStatementId);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sql);
            mappedStatement.setSqlCommandType("select");
            this.configuration.getMappedStatementMap().putIfAbsent(mappedStatementId, mappedStatement);
        });
    }

}
